package com.oa.ylms.apps.dao.news.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.oa.ylms.apps.constants.IDEDStates;
import com.oa.ylms.apps.dao.news.INewsCategoryDao;
import com.oa.ylms.apps.entity.news.NewsCategoryValue;

public class NewsCategoryDaoImpl extends HibernateDaoSupport implements INewsCategoryDao {
	
	private List<NewsCategoryValue> list;
	
	public int addNewsCategory(NewsCategoryValue newsCategory) throws Exception { 
		if (newsCategory != null) {
			this.getHibernateTemplate().save(newsCategory);
			return newsCategory.getCategoryId();
		}
		return 0;
	}


	@SuppressWarnings("unchecked")
	public List<NewsCategoryValue> queryCategoryByStates(final NewsCategoryValue newsCategory) throws Exception {
		String hqlStr ="FROM NewsCategoryValue ncv WHERE 1=1";
		if(newsCategory.getStates() != null){
			hqlStr += " AND ncv.states = ?";
		}
		hqlStr += " AND ncv.states <> ?";
		final String hql = hqlStr;
		list = this.getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				int index = -1;
				if(newsCategory.getStates() != null){
					query.setInteger(++index, newsCategory.getStates());
				}
				query.setInteger(++index, IDEDStates.DELETE);
				list = query.list();
				return list;
			}
		});
		return list;
	}

	public NewsCategoryValue queryCategoryById(NewsCategoryValue newsCategory) throws Exception {
		if(newsCategory!=null){
			return (NewsCategoryValue) this.getHibernateTemplate().get(NewsCategoryValue.class, newsCategory.getCategoryId());
		}
		return null;
	}

	@Override
	public boolean editNewsCategory(NewsCategoryValue newsCategory) {
		if (newsCategory != null) {
			try {
				this.getHibernateTemplate().update(newsCategory);
				return true;
			} catch (Exception e) {
			}
		}
		return false;
	}


	public List<NewsCategoryValue> getList() {
		return list;
	}


	public void setList(List<NewsCategoryValue> list) {
		this.list = list;
	}



}
